package cn.zswltech.gruul.common.dal.tkmybatis;

import com.github.pagehelper.Page;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.Collections;
import java.util.List;

/**
 * 通用分页结果对象 包含total和list，删除前端无用的page、pageSize等，并采用链式set方便组装
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
public class BasePage<T> {
    private long total;
    private List<T> list;

    public static<T> BasePage<T> emptyPage (long total) {
        return new BasePage<>(total, Collections.emptyList());
    }
    /**
     * page helper 转换PageResponse
     * @param sourceList 源list
     * @param resultList 目标list
     * @return
     */
    public static<T> BasePage<T> buildPage(List<?> sourceList, List<T> resultList) {
        BasePage<T> pageResponse = new BasePage<>();
        pageResponse.setList(resultList);
        if (sourceList instanceof Page) {
            Page page = (Page)sourceList;
            pageResponse.setTotal(page.getTotal());
        }
        return pageResponse;
    }

    /**
     * page helper 转换PageResponse
     * @param sourceList 源list
     * @return
     */
    public static<T> BasePage<T> buildPage(List<T> sourceList) {
        BasePage<T> pageResponse = new BasePage<>();
        pageResponse.setList(sourceList);
        if (sourceList instanceof Page) {
            Page page = (Page)sourceList;
            pageResponse.setTotal(page.getTotal());
        }
        return pageResponse;
    }
}
